/*
 *  animation.cc
 *  wonderland-project
 *
 *  Created by Ben Nolan on 20/10/08.
 *  Copyright 2008 Nolan Consulting Limited. All rights reserved.
 *
 */

#include "animation.h"

#include "vector.h"
#include "quaternion.h"
#include "v8defines.h"
#include "scripting_context.h"
#include "region.h"
#include "animation_manager.h"

namespace JSAnimation{
  
  v8::Handle<v8::ObjectTemplate> instance_template;
  v8::Handle<v8::FunctionTemplate> function_template;
  v8::Persistent<v8::Context> context_;
  
  Wonderland::Region *region_;

  V8_GETTER(Animation, name){
    return v8::String::New(V8INTERNAL(Ogre::Animation*)->getName().c_str());
  }

  V8CALLBACK(Animation,enable){ 
    V8INTERNAL(Ogre::AnimationState*)->setEnabled(true);

    region_->getAnimationManager()->addAnimation(V8INTERNAL(Ogre::AnimationState*));
    
    return v8::Undefined();
  }

  /* Construct a new node - doesnt actually allocate the node, use world.createAnimation for that */
  V8CALLBACK(Animation,create){
    v8::Persistent<v8::Object> self = v8::Persistent<v8::Object>::New(args.Holder());
    return self;
  }

  /* Sets internal fields with our idiom of storing the class name in the second field */
  void setInternalFields(v8::Persistent<v8::Object> p, Ogre::AnimationState *n){
    p->SetInternalField(0, v8::External::New(n));
    p->SetInternalField(1, v8::String::New("Animation"));
  }

  /* Only called from c++ */
  v8::Handle<v8::Value> New(Ogre::AnimationState *n){
    context_->Enter();

    v8::Persistent<v8::Object> instance = v8::Persistent<v8::Object>::New(function_template->GetFunction()->NewInstance());
    setInternalFields(instance, n);
    return instance;
  }

  void Initialize(Wonderland::ScriptingContext *sc, Wonderland::Region *region){
    context_ = sc->getContext();
    region_ = region;

    // Function Template
    function_template = v8::FunctionTemplate::New(Animation_create);
    function_template->SetClassName(v8::String::New("Animation"));

    // Instance template
    instance_template = function_template->InstanceTemplate();
    instance_template->SetInternalFieldCount(2);

    #define V8REGISTER(function) instance_template->Set(#function, v8::FunctionTemplate::New(Animation_ ## function));
    
    instance_template->SetAccessor(v8::String::New("name"), Animation_getname);
    V8REGISTER(enable);
  }

}

